package com.cetccst.securitysuite.uicomponents.watermark;

import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

public class WaterMark {
    private boolean isShowTime;
    private String[] labels;

    public WaterMark(boolean isShowTime, String[] labels) {
        this.isShowTime = isShowTime;
        this.labels = labels;
    }

    public boolean isShowTime() {
        return isShowTime;
    }

    public String[] getLabels() {
        return labels;
    }

    public static void handleConfigChanged(Activity activity, WaterMark config) {
        try {
            if (activity != null) {
                View contentView = refresh(activity, config);
                if (contentView != null) {
                    contentView.postInvalidate();
                }
            }
        } catch (Exception e) {
        }
    }

    public static View refresh(Activity activity, WaterMark config) {
        View decorView = activity.getWindow().getDecorView();
        final FrameLayout contentView = decorView.findViewById(android.R.id.content);
        try {
            for (int i = contentView.getChildCount() - 1; i >= 0; i--) {
                View view = contentView.getChildAt(i);
                if (view instanceof WaterMarkTextView) {
                    if (config == null) {
                        contentView.removeView(view);
                        return contentView;
                    }
                    update((WaterMarkTextView) view, config);
                    return contentView;
                }
            }

            if (config != null) {
                final WaterMarkTextView waterMarkTextView = new WaterMarkTextView(activity);
                update(waterMarkTextView, config);
                contentView.addView(waterMarkTextView);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return contentView;
    }

    private static void update(WaterMarkTextView waterMarkTextView, WaterMark config) {
        if (config != null) {
            boolean showTime = config.isShowTime();
            String[] labels = config.getLabels();

            waterMarkTextView.setWaterMarkText(labels);
            waterMarkTextView.setShowTime(showTime);
            waterMarkTextView.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            waterMarkTextView.postInvalidate();
        }
    }
}
